package com.aliyunexample;

import android.util.Log;

import com.aliyun.identity.platform.api.IdentityCallback;
import com.aliyun.identity.platform.api.IdentityPlatform;
import com.aliyun.identity.platform.api.IdentityResponse;
import com.aliyun.identity.platform.api.IdentityResponseCode;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

class AliyunModule extends ReactContextBaseJavaModule {

    private final ReactApplicationContext reactContext;
    private final String TAG = "AliyunModule";

    public AliyunModule(@Nullable ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @NonNull
    @Override
    public String getName() {
        return "RNAliyun";
    }

    @ReactMethod
    public void init() {
        IdentityPlatform.getInstance().install(reactContext);
        Log.d(TAG, "init: success");
    }

    @ReactMethod
    public void getMetaInfo(
            Promise promise
    ) {
        String metaInfo = IdentityPlatform.getMetaInfo(reactContext);
        Log.d(TAG, "getMetaInfo: success, value: " + metaInfo.toString());
        promise.resolve(metaInfo);
    }

    @ReactMethod
    public void getCertifyId(Promise promise) {
        // 将metaInfo发送到业务自己的服务器端，服务器端调用阿里云相关接口拿到certifyId，再返回给客户端。
        Log.d(TAG, "getCertifyId: success");
        promise.resolve("311deed69ac112b3964448776a0a6b77");
    }

    @ReactMethod
    public void faceVerify(String certifyId, Promise promise) {
        IdentityPlatform.getInstance().faceVerify(certifyId, null, new IdentityCallback() {
            @Override
            public boolean response(IdentityResponse identityResponse) {
                if(identityResponse.code == IdentityResponseCode.IDENTITY_SUCCESS) {
                    Log.d(TAG, "response: success");
                    promise.resolve("success");
                } else {
                    Log.d(TAG, "response: fail, message: " + identityResponse.message + " code:" + identityResponse.code);
                    promise.reject(new Error("error"));
                }
                return true;
            }
        });
    }
}
